package com.github.phoenics.militia.common.auth.jwt;

import org.springframework.security.core.context.SecurityContextHolder;
import com.github.phoenics.militia.common.auth.PasswordTextFun;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * JWT过滤器
 *
 * @author phoenics@126.com
 * @create 2018-09-10 19:07
 **/
public  class  JwtTokenFilter implements Filter {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(JwtTokenFilter.class);
    protected JwtService jwtService;
    protected PasswordTextFun t;

    public JwtTokenFilter(PasswordTextFun t,JwtService jwtService){
        this.t=t;
        this.jwtService=jwtService;
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        String authorization = servletRequest.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
                jwtService.parse(authorization.replaceAll("Bearer ", ""),t)
                        .ifPresent(jwtAuthentication -> SecurityContextHolder
                                .getContext()
                                .setAuthentication(jwtAuthentication));
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
